package com.tsq.weixin.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsq.web.base.service.impl.BaseServiceImpl;
import com.tsq.weixin.api.form.WxQrCodeForm;
import com.tsq.weixin.api.model.WxQrCode;
import com.tsq.weixin.provider.mapper.WxQrCodeMapper;
import com.tsq.weixin.provider.service.WxQrCodeService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service("wxQrCodeService")
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class WxQrCodeServiceImpl extends BaseServiceImpl<WxQrCodeMapper, WxQrCode> implements WxQrCodeService {
    private final WxMpService wxService;

    @Override
    public WxMpQrCodeTicket createQrCode(String appid, WxQrCodeForm form) throws WxErrorException {
        WxMpQrCodeTicket ticket;
        if (form.getIsTemp()) {//创建临时二维码
            ticket = wxService.getQrcodeService().qrCodeCreateTmpTicket(form.getSceneStr(), form.getExpireSeconds());
        } else {//创建永久二维码
            ticket = wxService.getQrcodeService().qrCodeCreateLastTicket(form.getSceneStr());
        }
        WxQrCode wxQrCode = new WxQrCode(form);
        wxQrCode.setTicket(ticket.getTicket());
        wxQrCode.setUrl(ticket.getUrl());
        wxQrCode.setAppid(appid);
        if (form.getIsTemp()) {
            wxQrCode.setExpireTime(new Date(new Date().getTime() + ticket.getExpireSeconds() * 1000L));
        }
        super.save(wxQrCode);
        return ticket;
    }

    @Override
    public IPage<WxQrCode> queryPage(WxQrCode wxQrCode) {
        String sceneStr = wxQrCode.getSceneStr();
        String appid = wxQrCode.getAppid();
        long currentPage = wxQrCode.getCurrent();
        long pageSize = wxQrCode.getSize();

        return this.baseMapper.selectPage(new Page<WxQrCode>(currentPage,pageSize),
                new QueryWrapper<WxQrCode>()
                        .eq(!StringUtils.isEmpty(appid), "appid", appid)
                        .like(!StringUtils.isEmpty(sceneStr), "scene_str", sceneStr));
    }

    @Override
    public WxQrCode getById(Long id) {
        return super.getOne(new LambdaQueryWrapper<WxQrCode>().eq(WxQrCode::getId,id));
    }

    @Override
    public boolean removeByIds(List<Long> asList) {
        return super.removeByIds(asList);
    }
}
